/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xtd.facade.inventory;

import com.xtd.facade.AbstractFacade;
import com.xtd.model.inventory.Commodity;
import com.xtd.util.CommodityPropertyEnum;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;

/**
 *
 * @author Lu Yuanbin
 */
@Stateless
public class CommodityFacade extends AbstractFacade<Commodity> {

    public CommodityFacade() {
        super(Commodity.class);
    }

    public List<Commodity> search(String content, CommodityPropertyEnum code, String type) {
        if (content == null) {
            content = "";
        }
        String query = "";
        if (code != null) {
            query = " and c.property = " + code;
        }
        if (type != null) {
            query = query + " and c.type = " + type;
        }
        return getEntityManager().createQuery("select c from Commodity as c where c.name like :content or c.number like :content" + query).setParameter("content", "%" + content + "%").getResultList();
    }

    public List<Commodity> seach(CommodityPropertyEnum code) {
        if (code == null) {
            return new ArrayList();
        } else {
            return getEntityManager().createQuery("select c from Commodity as c where  c.property = :code").setParameter("code", code).getResultList();

        }
    }

    public List<Commodity> seach(CommodityPropertyEnum code, String type) {
        if (code == null) {
            return new ArrayList();
        } else {
            return getEntityManager().createQuery("select c from Commodity as c where  c.property = :code and c.type = :type").setParameter("code", code).setParameter("type", type).getResultList();

        }
    }

    public void update(Commodity commodity) {
        if (commodity.getId() != null) {
            edit(commodity);
        } else {
            create(commodity);
        }
    }

    public List<Commodity> searchInadequateCommodities() {
        return getEntityManager().createQuery("select c from Commodity as c  where  (c.property = 2 || c.property = 4) and c.quantity < (select sum(oc.quantity-oc.returnedQuantity-oc.stockout) from OrderCommodity as oc where oc.commodity = c) and c.active is true").getResultList();
    }
}
